/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dale2507.gates.commands;

import dale2507.gates.GateDirectory;
import dale2507.gates.Messenger;
import dale2507.gates.data.permissions.Permissions;
import dale2507.gates.exceptions.PermissionException;
import dale2507.gates.gate.Gate;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

/**
 *
 * @author Dale
 */
public class ListGates implements CommandExecutor {

    @Override
    public boolean onCommand(CommandSender cs, Command cmnd, String string, String[] strings) {
        try {
            if (cs instanceof Player) this.checkPermissions((Player) cs, "");
            
            int page = 0;
            if (strings.length > 0) {
                try {
                    page = Integer.parseInt(strings[0]);
                } catch (NumberFormatException ex) {
                    // Do nothing
                }
            }

            Gate[] gates = GateDirectory.getInstance().getGates(cs, page);

            Messenger.sendMessage(cs, Messenger.INFO, "Gate Name");
            for (Gate g : gates) {
                Messenger.sendMessage(cs, Messenger.INFO, g.getSettings().getName());
            }
            return true;
        } catch (PermissionException ex) {
            Messenger.sendMessage(cs, Messenger.ERROR, ex.getMessage());
            return true;
        }
    }

    private void checkPermissions(Player p, String world) throws PermissionException {        
        World w = null;
        if (world != null && !world.isEmpty()) {
            w = Bukkit.getWorld(world);
        } else if (p != null) {
            p.getWorld();
        }
        
        if (!Permissions.getPermissions().getCommandPermissions().allowGateListPublic(p)) {
            throw new PermissionException("You are not allowed to use that command.");
        }
    }
    
}
